<template>
  <ele-page flex-table>
    <ComHeader title="新建入库通知单" @back="goBack()" />
    <ele-bottom-bar :teleported="true">
      <template #extra>
        <!-- <el-button type="" :loading="loading" @click="save('DR')">草稿</el-button> -->
        <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
      </template>
    </ele-bottom-bar>

    <el-scrollbar>
      <div flex-table>
        <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="form" :rules="rules" label-width="auto">
          <ele-card :body-style="{ paddingBottom: '5px' }" class="mb-10px!">
            <el-row :gutter="20">
              <el-col :md="6">
                <el-form-item label="货主" prop="supplier_id">
                  <el-select
                    v-model="form.supplier_id"
                    placeholder="请选择货主"
                    clearable
                  >
                    <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :md="6">
                <el-form-item label="仓库" prop="warehouse_id">
                  <el-select v-model="form.warehouse_id" :disabled="!form.supplier_id" placeholder="请选择仓库" clearable>
                    <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :md="6">
                <el-form-item label="来源单号" prop="obj_sn">
                  <el-input v-model="form.obj_sn" clearable placeholder="来源单号（选填）" />
                </el-form-item>
              </el-col>

              <el-col :md="18">
                <el-form-item label="订单备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" autosize clearable placeholder="请填写备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </ele-card>
          <ele-card :body-style="{ paddingBottom: '5px' }">
            <el-form-item label="商品信息" label-position="top" label-width="200px" prop="product">
              <template #label>
                <span class="flex-inline items-center">
                  <div class="">商品信息</div>
                  <div class="ml-12px">
                    <el-button
                      type="primary"
                      icon="IconElPlus"
                      :disabled="!form.supplier_id || !form.warehouse_id"
                      plain
                      @click="showProduct = true"
                    >
                      新增商品
                    </el-button>
                  </div>
                </span>
              </template>
              <el-table
                ref="tableRef"
                :data="form.product"
                size=""
                border
                style="width: 100%"
                show-summary
                :summary-method="getSummaries"
              >
                <el-table-column type="index" label="序" width="60" align="center" />
                <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
                <el-table-column prop="product_code" label="商品编码" align="center" />
                <el-table-column prop="unit" label="主单位" align="center" />
                <el-table-column
                  prop="multi_unit"
                  label="商品数量"
                  align="center"
                  :min-width="200"
                >
                  <template #default="{ row, $index }">
                    <div class="flex-a">
                      <el-space>
                        <el-form-item
                          v-for="(item, i) in row.multi_unit"
                          :key="i"
                          :label-width="0"
                          :prop="`product[${$index}].multi_unit[${i}].num`"
                          :required="row.multi_unit.every(v => !Number(v.num))"
                        >
                          <el-input
                            v-model="item.num"
                            class="w-100px!"
                            placeholder="数量"
                            oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                          >
                            <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
                          </el-input>
                        </el-form-item>
                      </el-space>
                      <div v-if="row.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
                        = {{ totalUnit(row.multi_unit) }}{{ row.unit }}
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  prop="price"
                  label="价格"
                  align="center"
                  :min-width="100"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :label-width="0"
                      :prop="`product[${$index}].price`"
                    >
                      <el-input
                        v-model="row.price"
                        placeholder="价格"
                        oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/,'$1')"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <!-- <el-table-column prop="cost_price" label="调拨价" align="center" /> -->

                <el-table-column label="操作" width="100" align="center">
                  <template #default="{ $index }">
                    <el-link type="danger" underline="never" @click="removeProduct($index)">删除</el-link>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </ele-card>
        </el-form>
      </div>
    </el-scrollbar>

    <SelectProduct
      v-model="showProduct"
      editPrice
      :selecteds="form.product"
      :where="{ supplier_id: form.supplier_id, warehouse_id: form.warehouse_id }"
      @done="selectProduct"
    />
  </ele-page>
</template>

<script setup>
import { listBanWarehouse, listSupplier } from '@/api/common'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'

const route = useRoute()
const router = useRouter()

const { routeTabKey, removePageTab } = utils.usePageTab()

const formRef = ref(null)
const tableRef = ref(null)

const { totalUnit } = utils

const orderId = ref(0)

/** 是否是修改 */
const isUpdate = computed(() => orderId.value > 0)

const loading = ref(false)

const warehouseList = ref([])

const showProduct = ref(false)

const [supplierList] = utils.useGetList(listSupplier)

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  id: undefined,
  supplier_id: '',
  warehouse_id: '',
  obj_sn: '',
  num: '',
  remark: '',
  product: [],
})

/** 表单验证规则 */
const rules = reactive({
  supplier_id: {
    required: true,
    message: '请选择货主',
    trigger: 'change',
  },
  warehouse_id: {
    required: true,
    message: '请选择仓库',
    trigger: 'change',
  },
  product: {
    required: true,
    message: '请选择商品',
    type: 'array',
    trigger: 'change',
    min: 1,
  },
})

function goBack(path) {
  if (!path)
    path = '/enter/notice'
  removePageTab({ key: routeTabKey })
  router.push(path)
}

onMounted(() => {
  orderId.value = Number(route.params?.id)
})

watch([() => form.supplier_id, () => form.warehouse_id], async (newVal, oldVal) => {
  if (oldVal?.[0] || oldVal?.[1]) {
    form.product = []
  }
  const newSupplierId = newVal[0]
  if (newSupplierId) {
    const res = await listBanWarehouse(newSupplierId)
    warehouseList.value = res.data
  }
  else {
    warehouseList.value = []
  }
  if (form.warehouse_id && !warehouseList.value.some(v => v.id === form.warehouse_id)) {
    form.warehouse_id = ''
  }
}, {
  immediate: true,
})

function save(status = undefined) {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    const formData = utils.cloneDeep(form)

    if (isUpdate.value) {
      formData.id = orderId.value
    }

    formData.product = formData.product.map((v) => {
      return {
        product_id: v.product_id,
        price: v.price,
        unit: v.multi_unit,
        num: totalUnit(v.multi_unit),
      }
    })

    formData.num = formData.product.reduce((acc, cur) => utils.Big(acc).plus(cur.num).valueOf(), 0)

    formData.status = status

    utils.post('/enterNotice/edit', formData)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          if (typeof res.data?.id === 'number' && res.data.id > 0) {
            goBack(`/enter/notice/info/${res.data.id}`)
          }
          else {
            goBack()
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

function selectProduct(data, row) {
  if (data.length) {
    data.forEach((v) => {
      v.multi_unit = utils.totalUnit(v.multi_unit) > 0 ? v.multi_unit : v.unit_list.map(d => ({ ...d, num: '' }))
    })
    form.product.push(...data)
  }
  else if (row) {
    const index = form.product.findIndex(v => v.product_id === row.product_id)
    if (index === -1) {
      form.product.push(row)
    }
    else {
      form.product[index] = row
    }
  }
}

function removeProduct(index) {
  form.product.splice(index, 1)
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['multi_unit']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => {
        const value = column.property === 'multi_unit' ? totalUnit(cur[column.property]) : cur[column.property]
        return utils.Big(acc).plus(value).valueOf()
      }, 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
